<template>
  <div class="app-container">
    <el-row>
      <el-col :span="10">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>
            <span>来源位置：</span>
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="(item, index) in sourceContainerLocation" :key="index">{{ item }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        <span style="font-size: 14px; font-weight: 400; line-height: 1">来源选择：</span>
        <el-button type="text" @click="handleSourceSelect">选择样本盒</el-button>
        <el-table v-if="selectSourceTubes && selectSourceTubes.length > 0" :key="tubeSourceKey"
                  :data="selectSourceTubes" :row-style="{'height': 540/selectSourceContainer.boxRow + 'px'}" border
                  class="customer-table"
                  height="590px" style="width: 583px; margin-left: 48px; margin-top: 16px" @cell-click="sourceCellClick"
        >
          <el-table-column align="center" type="index" width="42">
            <template slot-scope="scope">
              <span>{{ tubeRow[scope.$index] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-for="(item, index) in selectSourceTubes" :key="index" :label="index + 1 + ''"
                           :width="540/selectSourceContainer.boxColumn" align="center"
          >
            <template slot-scope="scope">
              <el-popover
                placement="right"
                trigger="hover"
                width="230"
              >
                <div v-if="scope.row[index].sample">
                  <div>样本状态：{{ sampStateFormat(scope.row[index].sample) }}</div>
                  <div><span>复份编号：{{ scope.row[index].sample.sampBackupCode }}</span></div>
                  <div><span>样本源名称：{{ scope.row[index].sample.sampSourceName }}</span></div>
                  <div><span>样本类型名称：{{ scope.row[index].sample.sampTypeName }}</span></div>
                  <div><span>样本组：{{ scope.row[index].sample.sampGroupName }}</span></div>
                  <div><span>条码/二维码：{{ scope.row[index].sample.qrCode }}</span></div>
                </div>
                <svg-icon v-if="scope.row[index].sample"
                          slot="reference"
                          :class="scope.row[index].sample.sampState === '1' ? 'table-icon' : 'table-icon-blur'"
                          :icon-class="scope.row[index].sample.sampTypeIcon"
                />
              </el-popover>
              <svg-icon v-if="scope.row[index].tubeState === '2'" class="table-icon" icon-class="disable"/>
              <svg-icon v-if="scope.row[index].tubeState === '1'" class="table-icon" icon-class="broken"/>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="4" style="text-align:center; margin-top: 52px; padding-left: 24px; padding-right: 24px">
        <el-button size="small" type="primary" @click="handleTransfer">
          <span>转移至<i class="el-icon-d-arrow-right"></i></span>
        </el-button>
        <div>
          <span
            style="float: left; font-size: 14px; font-weight: 400; line-height: 1; margin-bottom: 3px; margin-top: 16px"
          >转移描述</span>
          <el-input
            v-model="form.shiftDesc"
            :rows="10"
            placeholder="请输入转移描述"
            type="textarea"
          >
          </el-input>
        </div>
        <el-button v-hasPermi="['biobank:shiftSample:edit']" :loading="applying" size="small" style="margin-top: 32px"
                   type="success" @click="confirmShift"
        >确认转移
        </el-button>
      </el-col>
      <el-col :span="10">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>
            <span>目标位置：</span>
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="(item, index) in targetContainerLocation" :key="index">{{ item }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        <span style="font-size: 14px; font-weight: 400; line-height: 1">目标操作：</span>
        <el-button type="text" @click="handleTargetSelect">选择样本盒</el-button>
        <el-table v-if="selectTargetTubes && selectTargetTubes.length > 0" :key="tubeTargetKey"
                  :data="selectTargetTubes" :row-style="{'height': 540/selectTargetContainer.boxRow + 'px'}" border
                  class="customer-table"
                  height="590px" style="width: 583px; margin-left: 48px; margin-top: 16px" @cell-click="targetCellClick"
        >
          <el-table-column align="center" type="index" width="42">
            <template slot-scope="scope">
              <span>{{ tubeRow[scope.$index] }}</span>
            </template>
          </el-table-column>
          <el-table-column v-for="(item, index) in selectTargetTubes" :key="index" :label="index + 1 + ''"
                           :width="540/selectTargetContainer.boxColumn" align="center"
          >
            <template slot-scope="scope">
              <el-popover
                placement="right"
                trigger="hover"
                width="230"
              >
                <div v-if="scope.row[index].sample">
                  <div>样本状态：{{ sampStateFormat(scope.row[index].sample) }}</div>
                  <div><span>样本复份编号：{{ scope.row[index].sample.sampBackupCode }}</span></div>
                  <div><span>样本源名称：{{ scope.row[index].sample.sampSourceName }}</span></div>
                  <div><span>样本类型名称：{{ scope.row[index].sample.sampTypeName }}</span></div>
                  <div><span>样本组：{{ scope.row[index].sample.sampGroupName }}</span></div>
                  <div><span>条码/二维码：{{ scope.row[index].sample.qrCode }}</span></div>
                </div>
                <svg-icon v-if="scope.row[index].sample"
                          slot="reference"
                          :class="scope.row[index].sample.sampState === '1' ? 'table-icon' : 'table-icon-blur'"
                          :icon-class="scope.row[index].sample.sampTypeIcon"
                />
              </el-popover>
              <svg-icon v-if="scope.row[index].tubeState === '2'" class="table-icon" icon-class="disable"/>
              <svg-icon v-if="scope.row[index].tubeState === '1'" class="table-icon" icon-class="broken"/>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 容器树 对话框 -->
    <el-dialog :visible.sync="treeVisible" append-to-body title="选择冻存盒" width="40%">
      <el-tree
        ref="containerTree"
        :data="containerList"
        :expand-on-click-node="true"
        :highlight-current="highlightCurrent"
        :load="loadLazyTree"
        :props="containerTreeProps"
        lazy
        node-key="containerId"
        style="height: 480px; overflow: auto; min-width: 100%; display: inline-block"
        @node-click="treeNodeClick"
      >
          <span slot-scope="{ node, data }">
            <svg-icon :icon-class="data.containerIcon" style="margin-right: 3px"/>
            <span>{{ node.label }}</span>
            <span :style="judgeColor(data.storageRate)">{{ data.storageRate }}%</span>
          </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmBoxSelect">确 定</el-button>
        <el-button @click="cancelBoxSelect">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { lazyTree } from '@/api/biobank/container'
import { addShift } from '@/api/activiti/shift'
import { listTube } from '@/api/biobank/tube'

export default {
  name: 'ShiftSample',
  components: {},
  data() {
    return {
      // 来源table key 以强制刷新
      tubeSourceKey: '',
      // 目标table key 以强制刷新
      tubeTargetKey: '',
      // 来源盒
      selectSourceTubes: [],
      // 目标盒
      selectTargetTubes: [],
      // 来源 转移
      transferSource: {},
      // 目标 转移
      transferTarget: {},
      // 来源 old选中单元格
      oldSelectSourceCell: undefined,
      // 目标 old选中单元格
      oldSelectTargetCell: undefined,
      // 来源 选中的容器盒
      selectSourceContainer: {},
      // 目标 选中的容器盒
      selectTargetContainer: {},
      // 来源位置
      sourceContainerLocation: [],
      // 目标位置
      targetContainerLocation: [],
      // 容器树对话框
      treeVisible: false,
      // 容器树类型
      treeType: 'source',
      // 容器树是否高亮选中
      highlightCurrent: false,
      // 容器树 数据
      containerList: [],
      // 容器树
      containerTreeProps: {
        children: 'children',
        label: 'title',
        isLeaf: 'leaf'
      },
      // 表格行值
      tubeRow: this.GLOBAL.TUBE_ROW,
      // 样本状态
      sampStateOptions: [],
      // 转移描述
      shiftDesc: '',
      // 申请中
      applying: false,
      // 提交表单
      form: {
        shiftSamples: []
      }
    }
  },
  created() {
    this.getDicts('sample_state').then(response => {
      this.sampStateOptions = response.data
    })
  },
  methods: {
    /** 懒加载容器 列表 */
    loadLazyTree(node, resolve) {
      if (node.level === 0) {
        lazyTree(0).then(response => {
          resolve(response.data)
        })
      } else {
        lazyTree(node.data.containerId).then(response => {
          if (response.data && response.data.length > 0) {
            response.data.forEach(item => {
              if (item.containerTypeCode === 'box') {
                item.leaf = true
              }
            })
          }
          resolve(response.data)
        })
      }
    },
    // 容器树点击事件
    treeNodeClick(object, Node, element) {
      if (object.containerTypeCode === 'box') {
        this.highlightCurrent = true
        if (this.treeType === 'source') {
          this.selectSourceContainer = object
          this.sourceContainerLocation = this.selectSourceContainer.containerLocation.substr(1).split('/')
        } else if (this.treeType === 'target') {
          this.selectTargetContainer = object
          this.targetContainerLocation = this.selectTargetContainer.containerLocation.substr(1).split('/')
        }
      } else {
        this.highlightCurrent = false
      }
    },
    // 容器树存储率颜色
    judgeColor(rate) {
      if (rate === 0) {
        return 'color: #909399'
      } else if (rate >= 0 && rate < 40) {
        return 'color: #409EFF'
      } else if (rate >= 40 && rate < 60) {
        return 'color: #67C23A'
      } else if (rate >= 60 && rate < 80) {
        return 'color: #E6A23C'
      } else if (rate >= 80 && rate <= 100) {
        return 'color: #F56C6C'
      }
    },
    // 容器树对话框确定
    confirmBoxSelect() {
      this.treeVisible = false
      if (this.oldSelectSourceCell && Object.keys(this.oldSelectSourceCell).length > 0) {
        this.oldSelectSourceCell.removeAttribute('style')
        this.transferSource = {}
      }
      if (this.oldSelectTargetCell && Object.keys(this.oldSelectTargetCell).length > 0) {
        this.oldSelectTargetCell.removeAttribute('style')
        this.transferTarget = {}
      }
      if (this.treeType === 'source' && this.selectSourceContainer) {
        listTube(this.selectSourceContainer.containerId).then(response => {
          const tubes = response.data
          this.convertArray(tubes, this.treeType)
        })
      } else if (this.treeType === 'target' && this.selectTargetContainer) {
        listTube(this.selectTargetContainer.containerId).then(response => {
          const tubes = response.data
          this.convertArray(tubes, this.treeType)
        })
      } else {
        this.$message('请选择一个容器盒')
      }
    },
    // 一维数组转二维数组
    convertArray(tubes, type) {
      let row
      let column
      if (type === 'source') {
        row = this.selectSourceContainer.boxRow
        column = this.selectSourceContainer.boxColumn
        this.selectSourceTubes = []
      } else if (type === 'target') {
        row = this.selectTargetContainer.boxRow
        column = this.selectTargetContainer.boxColumn
        this.selectTargetTubes = []
      }

      let itemArr = []
      tubes.forEach(tube => {
        // 如果小数组满了，创建一个新的小数组
        if (itemArr.length === column) {
          itemArr = []
        }
        // 如果小数组是空的，将小数组保存到大数组中
        if (itemArr.length === 0) {
          if (type === 'source') {
            this.selectSourceTubes.push(itemArr)
          } else if (type === 'target') {
            this.selectTargetTubes.push(itemArr)
          }
        }
        // 保存数据到小数组
        itemArr.push(tube)
      })

      if (type === 'source') {
        this.tubeSourceKey = this.$uuid.v1()
      } else if (type === 'target') {
        this.tubeTargetKey = this.$uuid.v1()
      }
    },
    // 容器树对话框 取消按钮点击事件
    cancelBoxSelect() {
      this.treeVisible = false
    },
    // 来源 单元格点击事件
    sourceCellClick(row, column, cell, event) {
      let tableCell = row[parseInt(column.label) - 1]
      if (tableCell.tubeState === this.GLOBAL.TUBE.FORBIDDEN || tableCell.tubeState === this.GLOBAL.TUBE.DISABLE) { // tubeState === '2'  tubeState === '1'
        return false
      }
      if (!tableCell.sample || Object.keys(tableCell).length === 0) {
        return false
      }
      if (tableCell.sample.sampState !== this.GLOBAL.SAMPLE.NORMAL) {
        this.$message.warning('请选择正常在库的样本')
        return false
      }
      if (tableCell.sample.stockState === this.GLOBAL.STOCK_STATE.PROCESS) {
        this.$message.warning('当前选择样本已处于其他流程中，当前不允许操作，请重新选择')
        return false
      }
      if (this.oldSelectSourceCell) {
        this.oldSelectSourceCell.removeAttribute('style')
      }
      this.transferSource = tableCell
      cell.setAttribute('style', 'background:#409EFF')
      this.oldSelectSourceCell = cell
    },
    // 目标 单元格点击事件
    targetCellClick(row, column, cell, event) {
      let tableCell = row[parseInt(column.label) - 1]
      if (tableCell.tubeState === this.GLOBAL.TUBE.FORBIDDEN || tableCell.tubeState === this.GLOBAL.TUBE.DISABLE) { // tubeState === '2'  tubeState === '1'
        return false
      }
      if (tableCell.tubeState === this.GLOBAL.TUBE.OCCUPY) {
        this.$message.warning('当前选择单元格已被其他样本占用，请重新选择')
        return false
      }
      if (tableCell.sample && Object.keys(tableCell).length !== 0) {
        return false
      }
      if (this.oldSelectTargetCell) {
        this.oldSelectTargetCell.removeAttribute('style')
      }
      this.transferTarget = tableCell
      cell.setAttribute('style', 'background:#409EFF')
      this.oldSelectTargetCell = cell
    },
    // 来源选择事件
    handleSourceSelect() {
      this.treeType = 'source'
      this.treeVisible = true
    },
    // 目标选择事件
    handleTargetSelect() {
      this.treeType = 'target'
      this.treeVisible = true
    },
    // 样本状态状态字典翻译
    sampStateFormat(row, column) {
      return this.selectDictLabel(this.sampStateOptions, row.sampState)
    },
    // 转移至按钮点击事件
    handleTransfer() {
      if (!this.transferSource || Object.keys(this.transferSource).length === 0) {
        this.$message.warning('请选择来源位置')
        return false
      }
      if (!this.transferTarget || Object.keys(this.transferTarget).length === 0) {
        this.$message.warning('请选择目标位置')
        return false
      }

      let transfer = {}
      transfer.sampBackupId = this.transferSource.sampBackupId
      transfer.sampBackupCode = this.transferSource.sample.sampBackupCode
      transfer.sampSourceId = this.transferSource.sample.sampSourceId
      transfer.sampSourceName = this.transferSource.sample.sampSourceName
      transfer.sampSourceTypeId = this.transferSource.sample.sampSourceTypeId
      transfer.sampSourceTypeName = this.transferSource.sample.sampSourceTypeName
      transfer.sampTypeId = this.transferSource.sample.sampTypeId
      transfer.sampTypeName = this.transferSource.sample.sampTypeName
      transfer.oldTubeId = this.transferSource.tubeId
      transfer.newTubeId = this.transferTarget.tubeId
      transfer.oldContainerId = this.selectSourceContainer.containerId
      transfer.newContainerId = this.selectTargetContainer.containerId
      transfer.oldSampLocation = this.selectSourceContainer.containerLocation + '/' + this.transferSource.tubeLocation
      transfer.newSampLocation = this.selectTargetContainer.containerLocation + '/' + this.transferTarget.tubeLocation
      this.form.shiftSamples.push(transfer)

      let targetTubesArray = this.selectTargetTubes.reduce((prev, next) => {
        return prev.concat(next)
      })
      targetTubesArray.forEach(item => {
        if (item.tubeId === this.transferTarget.tubeId) {
          item.sample = this.transferSource.sample
          item.sampBackupId = this.transferSource.sampBackupId
        }
      })
      this.convertArray(targetTubesArray, 'target')

      let sourceTubesArray = this.selectSourceTubes.reduce((prev, next) => {
        return prev.concat(next)
      })
      sourceTubesArray.forEach(item => {
        if (item.tubeId === this.transferSource.tubeId) {
          item.sample = undefined
          item.sampBackupId = 0
        }
      })
      this.convertArray(sourceTubesArray, 'source')

      if (this.oldSelectSourceCell && Object.keys(this.oldSelectSourceCell).length > 0) {
        this.oldSelectSourceCell.removeAttribute('style')
        this.transferSource = {}
      }
      if (this.oldSelectTargetCell && Object.keys(this.oldSelectTargetCell).length > 0) {
        this.oldSelectTargetCell.removeAttribute('style')
        this.transferTarget = {}
      }
    },
    // 确认转移按钮点击事件
    confirmShift() {
      if (!this.form.shiftSamples || this.form.shiftSamples.length === 0) {
        this.$message.info('请选择需转移的样本')
        return false
      }
      this.form.shiftTitle = this.$store.getters.nickName + '的转移样本申请'
      this.form.shiftType = this.GLOBAL.SHIFT_TYPE.SAMPLE
      this.applying = true
      addShift(this.form).then(response => {
        this.$message.success(`转移样本申请提交成功`)
        this.applying = false
        this.refresh()
      }, error => {
        this.applying = false
      })
    },
    // 刷新界面
    refresh() {
      this.$store.dispatch('tagsView/delCachedView', this.$route).then(() => {
        this.$nextTick(() => {
          this.$router.replace({
            path: '/redirect' + this.$route.fullPath
          })
        })
      })
    }
  }
}
</script>
<style scoped>
.table-icon {
  position: absolute;
  top: 10%;
  left: 10%;
  right: 10%;
  bottom: 10%;
  width: 80%;
  height: 80%;
  object-fit: cover;
}

.table-icon-blur {
  position: absolute;
  top: 10%;
  left: 10%;
  right: 10%;
  bottom: 10%;
  width: 80%;
  height: 80%;
  object-fit: cover;
  -webkit-filter: blur(2px);
}
</style>
